package com.gitee.ywj1352.pservlet;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 *
 * JNDI 获取对象
 * @author: yangwenjie.a
 * @date: 2021/7/5 19:20
 * @description:
 */
public class ApplicationContext {

    private Context context = null;

    private Context envContext = null;

    private static final String ENV_NAMING_KEY = "java:comp/env";

    private ApplicationContext() {
        try {
            context = new InitialContext();
            envContext =  getBean(Context.class, ENV_NAMING_KEY);
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }

    private static final ApplicationContext INSTANCE = new ApplicationContext();

    public static ApplicationContext getInstance() {
        return ApplicationContext.INSTANCE;
    }



    private  <T> T getBean(Class<T> calzz, Context context, String namingKey) {
        Object lookup = null;
        try {
            lookup = context.lookup(namingKey);
            return calzz.cast(lookup);
        } catch (NamingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public <T> T getBean(Class<T> calzz, String namingKey) {
        return getBean(calzz, context , namingKey);
    }

    /**
     * 获取 Env 配置类对象
     * @param calzz
     * @param namingKey
     * @param <T>
     * @return
     */
    public <T> T getEnvBean(Class<T> calzz, String namingKey) {
        return getBean(calzz, envContext , namingKey);
    }



}
